import hashlib
import os.path
import socket
import time

from flask import render_template, request, redirect, url_for, session, jsonify, g, current_app

from app import db
from app.models.models import User
from app.utils.common import login_user_data
from app.utils.get_ip import get_local_ips

from . import index_blp


#blueprint_4.使用admin_blp替代app装饰视图函数
@index_blp.route("/")
def index():
    return redirect(url_for(".main"))

@index_blp.route("/main")
@login_user_data
def main():
    #session: 3_取用session值（3/4）
    login_flag = session.get("login_flag")
    if g.user:
        if login_flag and login_flag == "success":
            users = db.session.query(User).all()
            ips = get_local_ips()

            # 转换为可序列化的字典列表
            users_data = [{
                "id": u.id,
                "name": u.name,
                "email": u.email
                # 只包含需要暴露的字段
            } for u in users]

            return render_template("main.html", users = users_data, ip=ips)

    return redirect(url_for(".login"))#这里用的是当前视图的login函数

@index_blp.route("/login", methods=["GET", "POST"])
def login():
    if request.method == 'POST':
        name = request.form.get("user")
        email = request.form.get("email")
        pwd = request.form.get("password") or None

        # 2.处理数据
        if not (email and name):
            ret = {
                "status": 2,
                "errmsg": "缺少参数，登录失败"
            }
            return jsonify(ret)

        #3.判断数据库用户名密码,得出user_ret
        # users = db.session.query(User).all()
        user = db.session.query(User).filter(User.email == email).first()
        if user:
            user = db.session.query(User).filter(User.name == name).first()

            if user and user.pwd:
                if pwd and pwd == user.pwd:
                    # session: 1_使用session替代cookie(1/4)
                    session["login_flag"] = "success"
                    session["user_id"] = user.id
                    ret = {
                        "status": 0,
                        "errmsg": "登录成功"
                    }
                else:
                    ret = {
                        "status": 3,
                        "errmsg": "用户账号或密码错误"
                    }
            elif user and not user.pwd:
                if pwd:
                    ret = {
                        "status": 3,
                        "errmsg": "用户账号或密码错误"
                    }
                else:
                    session["login_flag"] = "success"
                    session["user_id"] = user.id
                    ret = {
                        "status": 0,
                        "errmsg": "登录成功"
                    }
            else:
                ret = {
                    "status": 3,
                    "errmsg": "用户账号或密码错误"
                }
        else:
            ret = {
                "status": 4,
                "errmsg": "用户未注册"
            }

        return jsonify(ret)

    elif request.method == 'GET':
        return render_template("login.html")


@index_blp.route("/logout")
def logout():
    #session 4_清理session, 跳转到主页(4/4)
    session.clear()
    return redirect(url_for(".index"))

@index_blp.route("/register", methods=["GET", "POST"])
def register():
    if request.method == 'GET':
        return render_template("register.html")
    elif request.method == 'POST':
        #1.提取数据
        #request.args只能提取url中问号后面的数据
        #request.form可以提取body中的数据
        email = request.form.get("email")
        name = request.form.get("user")
        pwd = request.form.get("password")

        #2.处理数据
        if not (email and name):
            ret = {
                "status": 1,
                "errmsg": "缺少参数，注册失败"
            }
        else:
            # users = db.session.query(User).all()
            user = db.session.query(User).filter(db.or_(User.name == name, User.email == email)).first()

            if user:
                ret = {
                    "status": 2,
                    "errmsg": "用户名或邮箱已存在"
                }
                return jsonify(ret)

            user_id = email[:email.find("@")]
            new_user = User(user_id=user_id, name=name, email=email, pwd=pwd or None)
            db.session.add(new_user)
            db.session.commit()

            ret = {
                "status": 0,
                "errmsg": "注册成功"
            }

        #3.返回结果
        return jsonify(ret)         #建议使用，它可以修改response相应头中的Content-Type: application/json

@index_blp.route("/avatar")
@login_user_data
def avatar():
    if not g.user:
        return render_template(url_for(".login"))

    #print(current_app.root_path)

    if request.method == "GET":
        # 防CSRF攻击
        csrf_hash = hashlib.md5()
        csrf_hash.update(str(time.time()).encode("utf-8"))
        csrf_token = csrf_hash.hexdigest()
        session["csrf_token"] = csrf_token

        return render_template("avatar.html", user=g.uesr, csrf_token=csrf_token)
    elif request.method == "POST":
        # 防csrf攻击
        csrf_token = request.form.get("csrf_token")
        if csrf_token and csrf_token == session.get("csrf_token"):
            print("认证成功")
        else:
            return "csrf 认证失败"

        # 1.提取用户名，密码
        name = request.form.get("username")
        pwd = request.form.get("password")

        # 2.提取出文件，这个文件当作头像来对待
        f = request.files.get("avatar")
        if f:
            file_hash = hashlib.md5()
            file_hash.update(f.filename.encode("utf-8"))
            file_name = file_hash.hexdigest() + f.filename[f.filename.rfind("."):]
            file_path = os.path.join(current_app.root_path, "static/upload/", file_name)
            f.save(file_path)

            # 3.将数据库中对应的avatar字段值改为刚刚保存的图片
            g.user.avatar = os.path.join("/static/upload/", file_name)
            db.session.commit()

        # 4.重定向到.avatar
        return redirect(url_for(".avatar "))

@index_blp.route("/modify", methods=["GET", "POST"])
@login_user_data
def modify():
    if not g.user:
        return render_template(url_for(".login"))

    # 1.提取用户名，邮箱
    name = request.form.get("username")
    email = request.form.get("email")

    user = db.session.query(User).filter(User.email == email).first()
    db.session.delete(user)
    db.session.commit()

    ret = {
        "status": 0,
        "errmsg": "删除成功"
    }
    return jsonify(ret)

